<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-16
 * Time: 下午7:42
 */
namespace Institution\Controller;
use Think\Controller;
use Admin\Model\AuthRuleModel;
use User\Api\UserApi;
class AdminController extends Controller {
    protected function _initialize(){
        /*判断用户是否登录*/
        define('UID', is_login());
        if(!UID){
            $this->redirect('Public/login');
        }

        /* 读取数据库中的配置 */
        $config =   S('DB_CONFIG_DATA');
        if(!$config){
            $config =   api('Config/lists');
            S('DB_CONFIG_DATA',$config);
        }
        C($config); //添加配置

        /* 读取数据库中option的配置 */
        $option =   S('DB_OPTION_DATA');
        if(!$option){
            $option =   api('Config/option_lists');
            S('DB_OPTION_DATA',$option);
        }
//        var_dump($option);die;
        C($option); //添加配置


        /*判断用户是否是管理员*/
        define('IS_ROOT',is_admin());
        if(!IS_ROOT){
            $AUTH = new \Think\Auth();
            $rule = MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME;
			//var_dump($rule);exit;
            if(!$AUTH->check($rule,UID)){
                $this->error('未授权访问');
            }
        }

        //判断后台查新站默认设置并设置了学校  2016.7.20   teng
        $default = C('SCHOOL_CONFIG');
        if($default == 2)
        {
            $res = M('Option')->where('type=2 and name="school_config"')->select();
            if(!$res['value'])
            {
                foreach($res as $viem){
                    $arr['department_id']   = $viem['value'];
                    $arr['process_id']      = 0;
                    M('kjcx')->where("lqrq between '$viem[start_day]' and '$viem[end_day]'  and process_id = -2")->save($arr);  //符合条件的改变状态
                }
            }
            else
            {
                $this->error('请设置默认时间内的学校！');
            }
        }
        define('DEPARTMENT_ID',$this->getDepartment());
        $this->assign('__MENU__',$this->getMenus());
    }
    /*
     * 获取菜单
     */
    public function getMenus($controller=CONTROLLER_NAME){
        $map['pid'] = 0;
        $map['hide'] =0;
        $map['module'] ='Institution';
        if(!C('DEVELOP_MODE')){ // 是否开发者模式
            $where['is_dev']    =   0;
        }
        $menus['main']  =   M('Menu')->where($map)->order('sort asc')->field('id,title,url')->select();
        $id=array();
        $menus['child'] = array();
        foreach($menus['main'] as $key =>$item){
            $AUTH = new \Think\Auth();
            $rule = MODULE_NAME.'/'.$item['url'];
            if(!IS_ROOT && !$AUTH->check($rule, UID)){
                unset($menus['main'][$key]);
                continue;
            }
            if(CONTROLLER_NAME.'/'.ACTION_NAME == $item['url']){
                $menus['main'][$key]['class'] = 'active';
            }
            $id[]=$item['id'];
        }
//        $pid = M('Nav')->where("pid !=0 AND url like '%{$controller}/".ACTION_NAME."%'")->getField('pid');
        //查找二级菜单
            $map['pid']=array('IN',$id);
            $rs =M('Menu')->where($map)->field('url')->select();
            $urls=array();
            foreach($rs as $key=>$item){
                $urls []= $item['url'];
            }
            $map0 =array();
            $map0['module'] = 'Institution';
            $map0['url'] =array('IN',$urls);
            // 查找当前子菜单
            $rs = M('Menu')->where($map0)->field('pid')->select();
            $pid=array();
            foreach($rs as $key=>$item){
                if($item['pid']!=0){
                $pid[]=$item['pid'];}
            }
        if($pid) {
            // 查找当前主菜单
            $map1 = array();
            $map1['pid'] = array('IN', $pid);
            $rs = M('Menu')->where($map1)->select();
            $nav['pid'] = array();
            foreach ($rs as $key => $item) {
                $nav['pid'][] = $item['pid'];
            }
            foreach ($menus['main'] as $key => $item) {
                // 获取当前主菜单的子菜单项
                    $menus['main'][$key]['class'] = 'current';
                    //生成child树
                    $groups = M('Menu')->where(array('group' => array('neq', ''), 'pid' => $item['id']))->distinct(true)->getField("group", true);
                    //获取二级分类的合法url
                    $where = array();
                    $where['pid'] = $item['id'];
                    $where['hide'] = 0;
                    if (!C('DEVELOP_MODE')) { // 是否开发者模式
                        $where['is_dev'] = 0;
                    }
                    $second_urls = M('Menu')->where($where)->getField('id,url');
                if(!IS_ROOT){
                    // 检测菜单权限
                    $to_check_urls = array();
                    foreach ($second_urls as $key=>$to_check_url) {
                        $rule = MODULE_NAME.'/'.$to_check_url;
                        if($this->checkRule($rule, AuthRuleModel::RULE_URL,null))
                            $to_check_urls[] = $to_check_url;
                    }
                }
                    foreach ($groups as $g) {
                        $map = array('group' => $g);
                        if (isset($to_check_urls)) {
                            if (empty($to_check_urls)) {
                                // 没有任何权限
                                continue;
                            } else {
                                $map['url'] = array('in', $to_check_urls);
                            }
                        }
                        $map['pid'] = $item['id'];
                        $map['hide'] = 0;
                        if (!C('DEVELOP_MODE')) { // 是否开发者模式
                            $map['is_dev'] = 0;
                        }
                        $menuList = M('Menu')->where($map)->field('id,pid,title,url,tip')->order('sort asc')->select();
                        $menus['child'][$g] = list_to_tree($menuList, 'id', 'pid', 'operater', $item['id']);
                    }
                }
            }
//            var_dump($menus);
        return $menus;
    }
    final protected function checkRule($rule, $type=AuthRuleModel::RULE_URL, $mode='url'){
        static $Auth    =   null;
        if (!$Auth) {
            $Auth       =   new \Think\Auth();
        }
        if(!$Auth->check($rule,UID,$type,$mode)){
            return false;
        }
        return true;
    }
    protected function lists ($model,$where=array(),$order='',$field=true,$pan=''){
        $options    =   array();
        $REQUEST    =   (array)I('get.');
        if(is_string($model)){
            $model  =   M($model);
        }
        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);

        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        if(empty($where)){
            $where  =   array('status'=>array('egt',0));
        }
        if( !empty($where)){
            $options['where']   =   $where;
        }
        $where2 = 1;
        if($pan!=''){
            //得到该用户所有拥有的权限操作
            $cx_arr = M('cx_process')->where('department_id = '.DEPARTMENT_ID)->field('check_user,process_id,show_user_id')->select();
            $cx_arr1 = array();
            foreach($cx_arr as $k=>$v){
                if(strpos($v['check_user'],UID)!==false){
                    $cx_arr1[] = $v['process_id'];
                }
            }
            $cx_arr1=checkarr2($cx_arr1);
            $sq = join(',',$cx_arr1);
            if($sq==''){   //没有分配权限时为空
                return '-1';
            }
            $where2   .=   " and process_id in ($sq) ";
			
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        if($pan!=''){
            //判断是否有查新管理组
            $if_zu = M('AuthGroup')->where('title like "%查新管理%" and sid='.DEPARTMENT_ID)->getField('id');
            if($if_zu){
                $rule_id = M('AuthGroupAccess')->where('uid=  '.UID.' and group_id='.$if_zu)->getField('uid');
                if($rule_id){
                    $total   = $model->where('process_id in (0,-1,13,20) and department_id='.DEPARTMENT_ID)->count();
                }
            }else{
                $total   =   $model->where($where2)->where($options['where'])->count();
            }
        }else{
            $total   =   $model->where($options['where'])->count();
        }
        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if($total>$listRows){
            $page->setConfig('prev','上一页');
            $page->setConfig('next','下一页');
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %HEADER%');
        }
        $p =$page->show();
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$total);
        $options['limit'] = $page->firstRow.','.$page->listRows;
		
        $model->setProperty('options',$options);
		//var_dump($rule_id);exit;
        if($rule_id){

             $he = $model->where('process_id in (0,-1,13,20) and department_id='.DEPARTMENT_ID)->field($field)->select();
			 //$he = $model->table('k_kjcx a')->where('process_id in (0,-1,13,20) and department_id='.DEPARTMENT_ID)->join('k_user b on a.cx_user_name=b.id')->field($field)->select();
			 //echo $model->_sql();die;
			return $he;
        }else{ 
			// $he=$model->table('k_kjcx a')->where($where2)->where($options['where'])->join('k_user b on a.cx_user_name=b.id')->field($field)->select();
			// echo json_encode($options['where']);exit;
			
			$he=$model->where($where2)->where($options['where'])->field($field)->select();
			// echo $model->_sql();die;
			// $res = $model->getTableFields();
			// echo json_encode($res);exit;
			return $he;
        }
    }
	
	 protected function lists_new ($model,$where=array(),$order='',$field=true,$pan=''){
		
        $options    =   array();
        $REQUEST    =   (array)I('get.');
        if(is_string($model)){
            $model  =   M($model);
        }
        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);

        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        if(empty($where)){
            $where  =   array('status'=>array('egt',0));
        }
        if( !empty($where)){
            $options['where']   =   $where;
        }
        $where2 = 1;
		
        if($pan!=''){
            //得到该用户所有拥有的权限操作
            $cx_arr = M('cx_process')
			->where('department_id = '.DEPARTMENT_ID)
			->field('check_user,process_id,show_user_id')
			->select();
            $cx_arr1 = array();
            foreach($cx_arr as $k=>$v){
                if(strpos($v['check_user'],UID)!==false){
                    $cx_arr1[] = $v['process_id'];
                }
            }
            $cx_arr1=checkarr2($cx_arr1);
            $sq = join(',',$cx_arr1);
            if($sq==''){   //没有分配权限时为空
                return '-1';
            }
            $where2   .=   " and process_id in ($sq) ";
			
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        if($pan!=''){
            //判断是否有查新管理组
            $if_zu = M('AuthGroup')->where('title like "%查新管理%" and sid='.DEPARTMENT_ID)->getField('id');
			
            if($if_zu){
                $rule_id = M('AuthGroupAccess')->where('uid=  '.UID.' and group_id='.$if_zu)->getField('uid');
                if($rule_id){
                    $total   = $model->table('k_kjcx a')
					->join('k_user b on a.cx_user_name=b.id')
					->join('k_user c ON a.sh_user_name=c.id','LEFT')
					->where('process_id in (0,-1,13,20) and department_id='.DEPARTMENT_ID)
					->count();
                }
            }else{
                $total   =   $model->table('k_kjcx a')
				->join('k_user b on a.cx_user_name=b.id')
				->join('k_user c ON a.sh_user_name=c.id','LEFT')
				->where($where2)->where($options['where'])
				->count();
            }
        }else{
            $total   =   $model->table('k_kjcx a')
			->join('k_user b on a.cx_user_name=b.id')
			->join('k_user c ON a.sh_user_name=c.id','LEFT')
			->where($options['where'])
			->count();
        }
        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if($total>$listRows){
            $page->setConfig('prev','上一页');
            $page->setConfig('next','下一页');
            $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %HEADER%');
        }
        $p =$page->show();
        $this->assign('_page', $p? $p: '');
        $this->assign('_total',$total);
        $options['limit'] = $page->firstRow.','.$page->listRows;
		
        $model->setProperty('options',$options);
		//var_dump($rule_id);exit;
        if($rule_id){
            $he = $model->table('k_kjcx a')->join('k_user b ON a.cx_user_name=b.id')->where('process_id in (0,-1,13,20) and department_id='.DEPARTMENT_ID)->field($field)->select();
			return $he;
        }else{ 
			$he=$model->table('k_kjcx a')
			->join('k_user b ON a.cx_user_name=b.id','LEFT')
			->join('k_user c ON a.sh_user_name=c.id','LEFT')
			->where($where2)
			->where($options['where'])
			->field('a.*,b.username as b_cx_user_name,c.username as c_sh_user_name')
			->select();
			return $he;
        }
    }

    //根据用户ID得到机构ID
    protected function getDepartment(){
        $map['id'] = UID;
        $user = M('User');
        $data = $user->find(UID);
        return $data['department'];
    }


}